using System;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
using Se.Framework.Common.Config.Providers;

namespace Se.Framework.Web.Mvc
{
    public class ObjectRegistryControllerSelector : DefaultHttpControllerSelector
    {
        private readonly HttpConfiguration configuration;

        public ObjectRegistryControllerSelector(System.Web.Http.HttpConfiguration configuration) : base(configuration)
        {
            this.configuration = configuration;
        }

        public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
        {
            HttpControllerDescriptor result = null;
            try
            {
                result = base.SelectController(request);
            }
            catch (Exception ex)
            {
                var name = GetControllerName(request);
                result = new HttpControllerDescriptor(configuration, name, typeof(GenericApiController<>).MakeGenericType(TypeProviderManager.Default.GetTypeByClassName(name)));
            }
            return result;
        }
    }
}